﻿using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Foundation.ExtensionMethods;

namespace Foundation
{
    /// <summary>
    /// Base class for windows.
    /// </summary>
    public class WindowView : Window
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WindowView"/> class.
        /// </summary>
        public WindowView()
        {
            DataContextChanged +=
                (sender, args) =>
                    {
                        var viewModel = args.NewValue as ViewModel;
                        if (viewModel == null) return;
                        CommandBindings.AddRangeOnlyExclusiveItems(viewModel.CommandBindings);
                        viewModel.OnClosing += (o, e) => { if (!e.Cancel) Close(); };
                    };

            if (Equals(this, Application.Current.MainWindow)) return;
            SetBinding(TopmostProperty, new Binding("Topmost") {Source = Application.Current.MainWindow});
        }

        private Point LastPosition { get; set; }

        public void DragMove(object sender, MouseEventArgs e)
        {
            var currentPosition = e.GetPosition(this);

            if (e.LeftButton == MouseButtonState.Pressed && currentPosition != LastPosition &&
                !InputManager.Current.IsInMenuMode)
                DragMove();

            LastPosition = currentPosition;
        }
    }
}
